package com.mdg.nfc;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;

public class NFCWriteActivity extends Activity {

    private TextView mEditTv;
    private TextView mNoteTv;
    private Button mWriteAnytimeBtn;
    private Button mWriteOnceBtn;

    private IntentFilter[] mWriteTagFilters;
    private NfcAdapter nfcAdapter;
    private PendingIntent pendingIntent;
    private String[][] mTechLists;
    private Boolean ifWrite;
    private Boolean readonly = false;
    private String mText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfcwrite);

        mEditTv = (TextView) findViewById(R.id.tv_edit);
        mNoteTv = (TextView) findViewById(R.id.tv_note);
        mWriteAnytimeBtn = (Button) findViewById(R.id.btn_write_anytime);
        mWriteOnceBtn = (Button) findViewById(R.id.btn_write_once);
        ifWrite = false;

        init();
    }

    private void init() {
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        ndef.addCategory("*/*");
        mWriteTagFilters = new IntentFilter[]{ndef};
        mTechLists = new String[][]{new String[]{NfcA.class.getName()},
                new String[]{NfcF.class.getName()},
                new String[]{NfcB.class.getName()},
                new String[]{NfcV.class.getName()}};

        mWriteAnytimeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               if(!checkText()){
                   return;
               }
                ifWrite = true;
                readonly = false;
                displayControl(ifWrite);
            }
        });

        mWriteOnceBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!checkText()){
                    return;
                }
                // TODO  弹出对话框提示
                AlertDialog.Builder builer=new AlertDialog.Builder(NFCWriteActivity.this);
                builer.setMessage("目前是只读写入模式，写入一次后不能写入，是否确定?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ifWrite = true;
                        readonly = true;  // 设置只读
                        displayControl(ifWrite);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ifWrite = false;
                        readonly = false;  // 设置只读
                        displayControl(ifWrite);
                    }
                }).show();
//                ifWrite = true;
//                readonly = true;  // 设置只读
//                displayControl(ifWrite);
            }
        });

    }

    private boolean checkText() {
        mText = mEditTv.getText().toString().trim();
        if (mText.isEmpty()) {
            Toast.makeText(getApplicationContext(), "数据不能为空!",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        nfcAdapter.enableForegroundDispatch(this, pendingIntent,
                mWriteTagFilters, mTechLists);
    }

    @Override
    protected void onPause() {
        super.onPause();
        nfcAdapter.disableForegroundDispatch(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);


        if (ifWrite == true) {
            if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) ||
                    NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
                Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                Ndef ndef = Ndef.get(tag);
//                Toast.makeText(getApplicationContext(), ndef.canMakeReadOnly() + "", Toast.LENGTH_SHORT).show();
                try {
                    //数据的写入过程一定要有连接操作
                    ndef.connect();
                    //构建数据包，也就是你要写入标签的数据
                    NdefRecord ndefRecord = new NdefRecord(
                            NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(),
                            new byte[]{}, mText.getBytes());
                    NdefRecord[] records = {ndefRecord};
                    NdefMessage ndefMessage = new NdefMessage(records);
                    ndef.writeNdefMessage(ndefMessage);
                    if (readonly) {
                        // 如果选择了只读模式  设置只读  只能设置一次
                        ndef.makeReadOnly();
                    }
                    Toast.makeText(getApplicationContext(), "数据写入成功! ",
                            Toast.LENGTH_SHORT).show();
                    displayControl(false);
                    ifWrite=false;
                } catch (IOException e1) {
                    e1.printStackTrace();
                    Toast.makeText(getApplicationContext(), "写入失败，芯片损坏或被设为只读! ",
                            Toast.LENGTH_SHORT).show();
                    displayControl(false);
                    ifWrite=false;
                } catch (FormatException e) {

                }
            }
        }
    }

    private void displayControl(boolean b) {
        if (b) { // 准备写入
            mNoteTv.setVisibility(View.VISIBLE);
            mEditTv.setVisibility(View.INVISIBLE);
            mWriteAnytimeBtn.setVisibility(View.INVISIBLE);
            mWriteOnceBtn.setVisibility(View.INVISIBLE);
            return;
        }
        mNoteTv.setVisibility(View.INVISIBLE);
        mEditTv.setVisibility(View.VISIBLE);
        mWriteAnytimeBtn.setVisibility(View.VISIBLE);
        mWriteOnceBtn.setVisibility(View.VISIBLE);
    }

}
